import { PlusBase } from "./PlusBase";

const Koa = require("koa");
const cors = require("koa2-cors");
const router = require("koa-router")();
import http = require('http');
import { join } from "path";
import { readdirSync } from "fs";
import { BaseService, RegistMethodVo } from "./httpServer/BaseService";
import { ClsUtils } from "../utils/ClsUtils";
import { IGlobal } from "../Index";
const bodyParser = require('koa-bodyparser');
const koaBody = require('koa-body');
const koaStatic = require('koa-static')
const path = require('path')

declare var global: IGlobal;
export class PlusHttpServer extends PlusBase {
    static NAME: string = "httpServer";
    private _port: number;
    private _path: string;
    private _publicPath: string;
    constructor(port: number, path: string, publicPath?: string) {
        super(PlusHttpServer.NAME);
        this._port = port;
        this._path = path;
        this._publicPath = publicPath;
    }

    async init() {
        var app = new Koa(global.config.koa);
        var server = http.createServer(app.callback());
        app.use(cors());
        // app.use(bodyParser());
        app.use(koaBody({
            multipart: true,
        }));
        this._publicPath && app.use(koaStatic(this._publicPath));
        var files = readdirSync(this._path);
        var js_files = files.filter((f) => {
            return f.endsWith('.js');
        });

        for (var f of js_files) {
            // logUtil.info(`process server: ${f}...`);
            // 导入js文件:
            let mapping = require(join(this._path, f));
            for (var key in mapping) {
                if (ClsUtils.targetIsCls(mapping[key], BaseService)) {
                    var service: BaseService = new mapping[key]();
                    for (var i = 0; i < service.methods.length; i++) {
                        let methodVo: RegistMethodVo = service.methods[i];
                        let url = "/" + (methodVo.uri || (key + "/" + methodVo.name));
                        if (methodVo.method.toLocaleLowerCase() == "post") {
                            router.post(url, methodVo.execute);
                        } else if (methodVo.method.toLocaleLowerCase() == "get") {
                            router.get(url, methodVo.execute);
                        }
                    }
                }
            }
        }


        app.on('error', (err, ctx) => {
            this.log.error(`请求错误:\n来源ip:${ctx.ip}\n请求连接:${ctx.href}\n参数:${err.body}\n错误信息:${err.stack}`);
        });

        // add router middleware:
        app.use(router.routes());

        server.listen(this._port);
        this.mCompleteHandle();
    }
}